import requests
import json
import random
import json
from hashlib import md5

headers = {'Content-Type': 'application/x-www-form-urlencoded'}
def t_baidu(word,appid,appkey,kind="en"):
    try:
        from_lang = 'auto'
        to_lang =  kind

        endpoint = 'http://api.fanyi.baidu.com'
        path = '/api/trans/vip/translate'
        url = endpoint + path

        query = word

        salt = random.randint(32768, 65536)
        sign = md5((appid + query + str(salt) + appkey).encode('utf-8')).hexdigest()

        payload = {'appid': appid, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}

        r = requests.post(url, params=payload, headers=headers)
        result = r.json()
        res= result["trans_result"][0]["dst"]
        return res
    except:
        return "1error"

